package com.yzy.controller;


import com.yzy.annotation.UserLoginToken;
import com.yzy.entity.User;
import com.yzy.service.TokenService;
import com.yzy.service.UserService;
import com.yzy.util.FileUtil;
import com.yzy.util.Message;
import com.yzy.util.ResponseCode;
import com.yzy.util.TokenUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private TokenService tokenService;

    @Resource
    private FileUtil fileUtil;

    @GetMapping("/all")
    public Object getAll(){

        List<User> list = userService.list();
        Map<String,List> map = new HashMap<>();
        map.put("data",list);

        return map;
    }
    /**
     * @description 登录接口
     * @param user 前端传来的
     * @return java.lang.Object
     * @author mgl
     * @date 2023/7/9 09:51
     */
    @PostMapping("/login")
    public Object login(@RequestBody User user){
        User one = userService.login(user);
        if(one != null) {
            String token = tokenService.getToken(one);
            Map<String,Object> map = new HashMap<>();
            map.put("token",token);
            map.put("userId",one.getId());
            return ResponseCode.buildSuccess(map, Message.LOGIN_SUCCESS);
        }else {
            return ResponseCode.buildFailed(Message.LOGIN_PASSWORD_ERROR);
        }
    }

    /**
     * @description 头像上传
     * @param avatar 图像文件
     * @return java.lang.Object
     * @author mgl
     * @date 2023/7/26 22:19
     */
    @PostMapping("/uploadAvatar")
    @UserLoginToken
    public Object uploadAvatar(MultipartFile avatar) {
        Integer userId = Integer.valueOf(TokenUtil.getTokenUserId());
        try {
            String avatarFile = fileUtil.transferAvatarFile(avatar);
            if (userService.changeAvatar(userId,avatarFile))
                return ResponseCode.buildSuccess(Message.AVATAR_UPLOAD_SUCCESS);
        } catch (Exception e) {
            return ResponseCode.buildFailed(e.getMessage());
        }
        return ResponseCode.buildFailed(Message.AVATAR_UPLOAD_FAILURE);
    }

    /**
     * @description 获取用户头像
     * @param userId 用户id
     * @param response http相应对象
     * @return java.lang.Object
     * @author mgl
     * @date 2023/7/26 22:40
     */
    @GetMapping("/getUserAvatar")
    public Object getAvatar(@RequestParam("userId") Integer userId, HttpServletResponse response) throws IOException {
        String filePath = userService.getAvatar(userId);
        java.io.File file = new java.io.File(filePath);
        if (!file.exists()) {
            return ResponseCode.buildFailed(Message.FILE_DOWNLOAD_NOT_PERMITTED);
        }

        String fileName = file.getName();
        // 重置response
        response.reset();
        // ContentType，即告诉客户端所发送的数据属于什么类型
        response.setContentType("application/octet-stream; charset=UTF-8");
        // 获得文件的长度
        response.setHeader("Content-Length", String.valueOf(file.length()));
        // 设置编码格式
        response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
        // 发送给客户端的数据
        OutputStream outputStream = response.getOutputStream();
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        // 读取文件
        bis = new BufferedInputStream(new FileInputStream(new java.io.File(filePath)));
        int i = bis.read(buff);
        // 只要能读到，则一直读取
        while (i != -1) {
            // 将文件写出
            outputStream.write(buff, 0, buff.length);
            // 刷出
            outputStream.flush();
            i = bis.read(buff);
        }
        return null;
    }

    @UserLoginToken
    @GetMapping("/getMoney")
    public Object getMoney(){
        Integer userId = Integer.valueOf(TokenUtil.getTokenUserId());
        User user = userService.getById(userId);
        Map<String,Double> map = new HashMap<>();
        map.put("money",user.getMoney());
        return ResponseCode.buildSuccess(map);
    }
    /**
     * @description 测试接口
     * @return java.lang.Object
     * @author mgl
     * @date 2023/7/9 11:18
     */
    @UserLoginToken
    @GetMapping("/test")
    public Object test(){
        String userId = TokenUtil.getTokenUserId();

        System.out.println(userId);
        return null;
    }

}
